/*
 * @Author: heinan
 * @Date: 2023-08-09 16:12:31
 * @Last Modified by: heinan
 * @Last Modified time: 2023-08-09 21:02:09
 */

"use strict";
const { Controller } = require("egg");

/**
 *  @Controller 评论管理
 */
class CommentController extends Controller {
  /**
   * @Summary 评论列表接口
   * @Description 获取评论分页列表
   * @Router GET /api/v1/comment
   * @Request query string uid 用户id
   * @Request query string pid 任意id查询
   * @Request query Number currentPage 页码 默认 1
   * @Request query Number pageSize 单页数量 默认 20
   */
  async index() {
    const result = await this.ctx.service.comment.index(this.ctx.query);
    if (result.data.length) {
      this.ctx.body = {
        code: 1,
        message: "查询成功!",
        data: result,
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "暂无数据!",
        data: [],
      };
    }
  }
  /**
   * @Summary 添加评论接口
   * @Description 添加评论接口
   * @Router POST /api/v1/comment
   * @Request body createComment *body
   */
  async create() {
    try {
      this.ctx.validate({
        uid: "string",
        pid: "string",
        comment_text: "string",
      });
    } catch (err) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        error: err.errors,
      });
    }
    const result = await this.ctx.service.comment.create(this.ctx.request.body);
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: "新增成功!",
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "新增失败!",
      };
    }
  }
  /**
   * @Summary 更新评论接口
   * @Description 根据评论id,更新评论内容
   * @Router PUT /api/v1/comment/{id}
   * @Request path string *id
   * @Request body updateComment *body
   */
  async update() {
    try {
      this.ctx.validate({
        comment_text: "string",
      });
    } catch (err) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        error: err.errors,
      });
    }
    const result = await this.ctx.service.comment.update({
      ...this.ctx.params,
      ...this.ctx.request.body,
    });
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: "修改成功!",
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "修改失败!",
      };
    }
  }
  /**
   * @Summary 删除评论接口
   * @Description 根据评论id删除评论
   * @Router DELETE /api/v1/comment/{id}
   * @Request path string *id
   */
  async destroy() {
    const result = await this.ctx.service.comment.destroy(this.ctx.params);
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: "删除成功!",
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "删除失败!",
      };
    }
  }
}

module.exports = CommentController;
